package com.xinnet.mms.user.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xinnet.core.utils.DateUtil;
import com.xinnet.core.utils.DigestsUtil;
import com.xinnet.core.utils.EncodesUtil;
import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.entity.User;
import com.xinnet.mms.user.dao.UserDao;
import com.xinnet.mms.user.service.UserService;


@Service("userService")
public class UserServiceImpl implements UserService {
	private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	@Autowired
	private UserDao userDao;
	
	public PageView<User> query(PageView<User> pageView, User user) {
		List<User> list = userDao.query(pageView, user);
		pageView.setRecords(list);
		return pageView;
	}
	public void add(User user) {
		entryptPassword(user);
		user.setRoles("user");
//		user.setRegisterDate(DateUtil.getTimestamp(new Date()));
		userDao.add(user);
	}
	public void delete(Long id) {
		userDao.delete(id);
	}
	public void modify(User user) {
		if (StringUtils.isNotBlank(user.getPlainPassword())) {
			entryptPassword(user);
		}
		userDao.modify(user);
	}
	public User getById(Long id) {
		return userDao.getById(id);	
	}
	public User findByUserName(String userName) {
		return userDao.findByUserName(userName);
	}
	
	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private  static void entryptPassword(User user) {
		byte[] salt = DigestsUtil.generateSalt(SALT_SIZE);
		user.setSalt(EncodesUtil.encodeHex(salt));

		byte[] hashPassword = DigestsUtil.sha1(user.getPlainPassword().getBytes(), salt, HASH_INTERATIONS);
		user.setPassword(EncodesUtil.encodeHex(hashPassword));
	}
	
	public static void main(String[] args){
		User user = new User();
		user.setPlainPassword("123123");
		user.setSalt("9666dd5572441c0d");
		entryptPassword(user);
		System.out.println(user.getPassword());
		System.out.println(user.getSalt());
	}

}
